import { CloudDBZoneWrapper } from '../clouddb/CloudDBZoneWrapper.js';
import * as Utils from '../utils/Utils';
import * as bornInsert from '../born-insert/Handler';

const TAG: string = "cloudDB-->"

/**
 event:{"bornYear":2018}
 */
export const myHandler = async function (event, context, callback, logger) {
  const credential = Utils.getCredential(context, logger);

  try {
    const cloudDBZoneWrapper = new CloudDBZoneWrapper(credential, logger);
    const result = await cloudDBZoneWrapper.queryDataByYear(event.bornYear);
    if (result && result.length > 0) { //如果据库中有，则直接查询显示
      callback({
        ret: { code: 0, desc: "SUCCESS" },
        result: [...result]
      });
    } else { // 如果数据库中没有，则计算出结果，然后再插入数据库
      let bornName = animal(parseInt(event.bornYear));
      let bornInfo = { "bornYear": parseInt(event.bornYear), "bornName": bornName }
      try {
        bornInsert.myHandler(bornInfo, context, callback, logger);
        callback({
          ret: { code: 0, desc: "SUCCESS" },
          result: [bornInfo]
        });
      } catch (err) {
        callback({
          ret: { code: -1, desc: "FAILED" }
        });
        logger.error(TAG + "插入数据库失败！")
      }
    }
  } catch (err) {
    logger.error(TAG + "func error:" + err.message + " stack:" + err.stack);
    callback({
      ret: { code: -1, desc: "ERROR" },
    });
  }

};

function animal(inputYear) {
  var resultString;
  if (!isNumber(inputYear)) {
    resultString = "input is not a number";
  } else {
    var remainder = inputYear % 12;
    switch (remainder) {
      case 0:
        resultString = "猴";
        break;
      case 1:
        resultString = "鸡";
        break;
      case 2:
        resultString = "狗";
        break;
      case 3:
        resultString = "猪";
        break;
      case 4:
        resultString = "鼠";
        break;
      case 5:
        resultString = "牛";
        break;
      case 6:
        resultString = "虎";
        break;
      case 7:
        resultString = "兔";
        break;
      case 8:
        resultString = "龙";
        break;
      case 9:
        resultString = "蛇";
        break;
      case 10:
        resultString = "马";
        break;
      case 11:
        resultString = "羊";
        break;
      default:
        resultString = "No symbolic Animal";
    }
  }
  return resultString;
}

function isNumber(input) {
  if (parseInt(input).toString() == "NaN") {
    return false;
  } else {
    return true;
  }
}